#include<iostream>
#include<cstring>
#include<cstdlib>
#include<cstdio>
#include<unistd.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>


using namespace std;

#define N 2
#define nums 1024

void Write(int wfd)
{
    string s="i am a child process";
    pid_t self=getpid();
    int num=0;
    char buffer[nums];
    while(true)
    {   buffer[0]=0;
        snprintf(buffer,sizeof(buffer),"%s-%d-[%d]",s.c_str(),self,num++);

        //发送写入信息让父进程读取
        write(wfd,buffer,strlen(buffer));
        sleep(1);
    }
}

void Read(int rfd)
{
    char buffer[nums];
    while(true)
    {
        //父进程读取信息
        ssize_t n=read(rfd,buffer,sizeof(buffer));
        if(n>0)
        {
            buffer[n]=0;
            cout<<"i am a father processor["<<getpid()<<"]-----~"<<buffer<<endl;
        }
    }
}

int main()
{
    int pipefd[N]={0};
    int n= pipe(pipefd);
    if(n<0) return 1;

    //子进程写  父进程读
    pid_t id=fork();
    if (id<0) return 3;
    if(id==0)
   {
        //子进程
        close(pipefd[0]);//先关闭管道的读权限
        Write(pipefd[1]);

        close(pipefd[1]);
    }
    //父进程

    close(pipefd[1]);//先关闭管道的写程序

    Read(pipefd[0]);
    pid_t rid=waitpid(id,nullptr,0);
    if(rid<0)  return 3;

    close(pipefd[0]);
    return 0;
}

